import React from 'react';
import ReactDOM from 'react-dom'
import { Table, Icon, Button, Tooltip, Tag } from 'antd'
import Condition from 'components/condition'
import ColumnsConfig from 'components/custom-table/columns-config'
import ExportConfig from 'components/custom-table/export-config'
import FilterConfig from 'components/custom-table/filter-config'
import 'styles/components/custom-table.scss'
import { deepCopy, messages } from "share/common";
const { If } = Condition;

class CustomTable extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      columns: [],
      showColumnsConfig: false,
      showExportConfig: false,
      showFilterConfig: false,
      hasFixed: false,
      scrollX: 0,
      tableWidth: 0,
      filterItems: [],
      currentFilter: 0
    }
  }

  componentDidMount(){
    const { allColumns } = this.props;
    let columns = deepCopy(allColumns);
    this.setState({ columns }, () => {
      let mainDom = ReactDOM.findDOMNode(this.refs.main);
      let tableWidth = parseInt(mainDom.getBoundingClientRect().width);
      //预防后来的自定义这两列的宽度，这个版本先固定
      let selection = mainDom.getElementsByClassName('ant-table-selection-column');
      let expand = mainDom.getElementsByClassName('ant-table-expand-icon-th');
      if(selection.length > 0){
        tableWidth -= 62;
      }
      if(expand.length > 0){
        tableWidth -= 50;
      }
      this.setState({ tableWidth });
    });
  }

  componentWillReceiveProps(nextProps) {}

  handleCloseColumnsConfig = result => {
    this.setState({ ...result, showColumnsConfig: false })
  };

  handleCloseExportConfig = () => {
    this.setState({ showExportConfig: false });
  };

  handleCloseFilterConfig = () => {
    this.setState({ showFilterConfig: false });
  };

  handleCloseFilterTag = (e, removedTag) => {
    e.stopPropagation();
    const { filterItems, searchParams} = this.state;
    const filter = filterItems.filter(tag => tag.id !== removedTag);
    let params = deepCopy(searchParams);
    params[removedTag] = null;
    this.setState({
      filterItems: filter,
      searchParams: params
    }, () => this.props.onChange(this.state.searchParams));
  };

  handleToggleFilterTag = removedTag => {
    const { filterItems, searchParams} = this.state;
    let params = deepCopy(searchParams);
    params[removedTag.id] = removedTag.checked ? null : removedTag.valueOid;
    const filter = filterItems.map(tag => {
      tag.id === removedTag.id && (tag.checked = !tag.checked);
      return tag;
    });
    this.setState({
      filterItems: filter,
      searchParams: params
    }, () => this.props.onChange(this.state.searchParams));
  };

  transformTag = (param, e) => {
    const { currentFilter } = this.state;
    let count = currentFilter;
    let node = e.target || e.currentTarget;
    let baseNode = node.parentNode.querySelector("#tag-container");
    if(param === "right") count < baseNode.childNodes.length - 1 && count++;
    if(param === "left") count > 0 && count--;
    let transform = 0, minCount = Math.min(count, baseNode.childNodes.length);
    for(let i = 0; i < minCount; i++){
      transform += baseNode.childNodes[i].offsetWidth;
    }
    baseNode.style.transform = `translateX(-${transform}px)`;
    baseNode.style.webkitTransform = `translateX(-${transform}px)`;
    baseNode.style.msTransform = `translateX(-${transform}px)`;
    baseNode.style.MozTransform = `translateX(-${transform}px)`;
    this.setState({ currentFilter: count })
  };

  onChange = (filterItems, searchParams) => {
    this.setState({ filterItems, searchParams }, () => this.props.onChange(this.state.searchParams));
  };

  render() {
    const { tableOption, showOperation, localKey, allColumns, source } = this.props;
    const {
      columns, showColumnsConfig, scrollX, hasFixed, tableWidth,
      showExportConfig, showFilterConfig, filterItems
    } = this.state;
    const { pagination, dataSource, rowSelection, scroll } = tableOption;
    const isFixed = tableOption.hasFixed;
    console.log('1111111', hasFixed, isFixed)
    let total = pagination ? pagination.total : dataSource.length;
    return (
      <div className={`custom-table ${showOperation ? '' : 'old-custom'}`}>
        <div className="table-container" ref="main">
          {showOperation ? (
            <div className="custom-table-header">
              <div className="table-header-title">
                共&nbsp;{total}&nbsp;条数据
                {rowSelection && rowSelection.type !== 'radio' &&
                  <span>&nbsp;&nbsp;/&nbsp;&nbsp;已选择&nbsp;{rowSelection.selectedRowKeys.length}&nbsp;条</span>
                }
              </div>
              <div className="table-button">
                <Tooltip title="筛选" onClick={() => this.setState({ showFilterConfig: true })}>
                  <Button icon="filter"/>
                </Tooltip>
                <Tooltip title="报表">
                  <Button icon="bar-chart"/>
                </Tooltip>
                <Tooltip title="分类">
                  <Button icon="bars"/>
                </Tooltip>
                <Tooltip title="导出" onClick={() => this.setState({ showExportConfig: true })}>
                  <Button icon="export"/>
                </Tooltip>
                <Tooltip title="调整">
                  <Button icon="setting" onClick={() => this.setState({ showColumnsConfig: true })}/>
                </Tooltip>
              </div>
            </div>
          ) : (
            <Tooltip
              title={<div style={{ whiteSpace: 'nowrap' }}>{messages('components.key946')/*自定义列*/}</div>}
              placement='topRight'
            >
              <div className="menu-icon" onClick={() => this.setState({ showColumnsConfig: true })}>
                <Icon type="setting" />
              </div>
            </Tooltip>
          )}
          <If value={filterItems.filter(f => f.value).length}>
            <div className="filter-box"> {messages('components.key870')/*筛选条件*/}：
              <Button
                shape="circle"
                icon="left"
                size="small"
                onClick={e => this.transformTag("left", e)}
              />
              <div id="tag-list">
              <span id="tag-container" >
                {filterItems.map(f => {
                  if(f.value)
                    return (
                      <Tag
                        key={f.id}
                        className={`filter-tag ${f.checked ? "checked" : ""}`}
                        closable
                        onClose={e => this.handleCloseFilterTag(e, f.id)}
                        onClick={() => this.handleToggleFilterTag(f)}
                      >
                        {f.label}：<span className="tag-value">{f.value}</span>
                      </Tag>)
                })}
              </span>
              </div>
              <Button
                shape="circle"
                icon="right"
                size="small"
                onClick={e => this.transformTag("right", e)}
              />
            </div>
          </If>
          <Table {...Object.assign(
            {},
            tableOption,
            {
              columns: columns.filter(c => c.selected),
              scroll: (hasFixed ? { x: scrollX } : isFixed ? {x: scroll && scroll.x} : {})
            },
          )}/>
        </div>
        <ColumnsConfig
          visible={showColumnsConfig}
          tableWidth={tableWidth}
          localKey={localKey}
          allColumns={allColumns}
          tableOption={tableOption}
          onClose={this.handleCloseColumnsConfig}
        />
        <ExportConfig
          visible={showExportConfig}
          allColumns={allColumns}
          onClose={this.handleCloseExportConfig}
        />
        {showOperation && <FilterConfig
          visible={showFilterConfig}
          onChange={(filterItems, searchParams) => this.onChange(filterItems, searchParams)}
          onClose={this.handleCloseFilterConfig}
          source={source}
        />}

      </div>
    );
  }
}

CustomTable.PropTypes = {
  localKey: React.PropTypes.string,
  tableOption: React.PropTypes.object,
  allColumns: React.PropTypes.array,
  showOperation: React.PropTypes.bool,
  source: React.PropTypes.object,
  onChange: React.PropTypes.func, //分页、排序、筛选变化时触发
};

CustomTable.defaultProps = {
  tableOption: Table.defaultProps,
  allColumns: []
};

export default CustomTable;
